//
//  Utility.m
//  haowan
//
//  Created by wupeijing on 3/12/15.
//  Copyright (c) 2015 iyaya. All rights reserved.
//

#import "Utility.h"
#import "TKFont.h"
#import "BaseNavigationController.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation Utility

+ (void)showSimpleMessage:(NSString *)msg {

}

+ (UIView *)createMaskViewWithFrame:(CGRect)frame action:(SEL)action onTarget:(id)target {
    UIView *maskView = [[UIView alloc] initWithFrame:frame];
    maskView.backgroundColor = [UIColor blackColor];
    maskView.alpha = 0.5f;

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
    [maskView addGestureRecognizer:tapGestureRecognizer];
    return maskView;
}

+ (UINavigationController *)presentWithANavigationController:(UIViewController *)contentVC from:(UIViewController *)presentingVC hasNavBar:(BOOL)hasNavBar {
    UINavigationController *presentedVC = (UINavigationController *)contentVC;
    if (![contentVC isKindOfClass:[UINavigationController class]]) {
        presentedVC = [[BaseNavigationController alloc] initWithRootViewController:contentVC];
    }
    UINavigationController *wrapper = (UINavigationController *)presentedVC;
    wrapper.navigationBar.hidden = !hasNavBar;

    presentingVC = presentingVC ?: [UIApplication sharedApplication].keyWindow.rootViewController;
    [presentingVC presentViewController:presentedVC animated:YES completion:nil];
    return presentedVC;
}

+ (void)closeViewController:(UIViewController *)vc {
    [self closeViewController:vc completion:nil ignoreQuitVC:NO];
}

+ (void)closeViewController:(UIViewController *)vc completion:(void (^)(void))completion {
    [self closeViewController:vc completion:completion ignoreQuitVC:NO];
}

+ (void)closeViewController:(UIViewController *)vc completion:(void (^)(void))completion ignoreQuitVC:(BOOL)ignore {
    if (!ignore && [vc conformsToProtocol:@protocol(QuitVCPropertyDelegate)]) {
        id<QuitVCPropertyDelegate> hasQuitVC = (id<QuitVCPropertyDelegate>)vc;
        UIViewController *vcNeedToQuit = hasQuitVC.quitVC;
        if (vcNeedToQuit) {
            hasQuitVC.quitVC = nil;
            [self closeViewController:vcNeedToQuit completion:completion];
            return;
        }
    }

    if (!vc.navigationController) {
        [vc dismissViewControllerAnimated:YES completion:completion];
    } else if ([vc.navigationController viewControllers][0] == vc) {
        [self closeViewController:vc.navigationController completion:completion];
    } else {
        [vc.navigationController popViewControllerAnimated:YES];
    }
}

+ (void)customizeNavigationBar {
    UIImage *image = [Utility createImageFromColor:[UIColor whiteColor] withSize:CGSizeMake(1, 1)];
    [[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    [UINavigationBar appearance].shadowImage = [Utility createImageFromColor:COLOR_CELL_LINE withSize:CGSizeMake(1, 1)];

    NSDictionary *ats = @{
                          NSFontAttributeName : [TKFont systemFontOfSize:18],
                          NSForegroundColorAttributeName : [UIColor blackColor]
                          };
    [UINavigationBar appearance].titleTextAttributes = ats;
}

+ (void)setNavigationBarWithTitleColor:(UIColor *)color andNavController:(UINavigationController *)navController
{
      [navController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:color}];
}

+ (UIButton *)createButtonWithTitle:(NSString *)title color:(UIColor *)color font:(UIFont *)font block:(ButtonBlockAction)block {
    UIButton *btn = [[UIButton alloc] init];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:color forState:UIControlStateNormal];
    [btn.titleLabel setFont:font];
    [btn sizeToFit];
    btn.tappedBlock = block;
    return btn;
}

+ (void)getDataFrom:(NSString *)url withBlock:(FunctionWithData)block {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if(data){
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                if (block) {
                    block(dic);
                }
            } else {
                if (block) {
                    block([NSDictionary dictionary]);
                }
            }
        });
    });
}

+ (UIImage *)createImageFromColor:(UIColor *)color withSize:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);

    CGFloat alpha = 0;
    [color getWhite:nil alpha:&alpha];
    UIGraphicsBeginImageContextWithOptions(rect.size, alpha > 0.99, 0);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

+ (UIImage *)createImageFromColor:(UIColor *)color
{
    return [self createImageFromColor:color withSize:CGSizeMake(1, 1)];
}

+ (NSArray *)splitString:(NSString *)rawString withMaxLength:(NSInteger)maxLength
{
    if (rawString.length < maxLength) {
        return [NSArray arrayWithObject:rawString];
    }
    
    NSMutableArray *splitedStringArray = [[NSMutableArray alloc] init];
    for (int i = 0 ; i < rawString.length / maxLength + 1 ; i++) {
        //        NSLog(@"from=%i to=%i total= %i", i * maxLength, MIN((i + 1) * maxLength, rawString.length - i * maxLength - 1), rawString.length);
        
        [splitedStringArray addObject:[rawString substringWithRange:NSMakeRange(i * maxLength, MIN((i + 1) * maxLength, rawString.length - i * maxLength))]];
    }
    
    return splitedStringArray;
}

#pragma mark - 最少返回12像素
+ (CGFloat)heightForText:(NSString*)contentText width:(CGFloat)width font:(UIFont *)font
{
    if ([contentText length] == 0) {
        return 12;
    }
    //    CGSize size=[contentText sizeWithFont:font constrainedToSize:CGSizeMake(width - kTextViewPadding * 2, CGFLOAT_MAX) lineBreakMode:0];
    CGSize size = [self sizeWithText:contentText boundingSize:CGSizeMake(width - kTextViewPadding * 2, CGFLOAT_MAX) font:font lineBreakMode:NSLineBreakByCharWrapping];
    
    return size.height + kTextViewPadding * 2;
}

#pragma mark - 根据字体，宽度返回 高度
+ (CGFloat)heightWithText:(NSString *)text font:(UIFont *)font width:(CGFloat)width minHeight:(CGFloat)minHeight
{
    if (text) {
        CGSize size = CGSizeZero;
        CGSize rSize = CGSizeMake(width, NSUIntegerMax);
        
        size = [self sizeWithText:text boundingSize:rSize font:font lineBreakMode:NSLineBreakByCharWrapping];
        
        if (size.height > minHeight) {
            return size.height;
        } else {
            return minHeight;
        }
    }
    
    return minHeight;
}


+ (CGFloat)heightWithText:(NSString *)text width:(CGFloat)width minHeight:(CGFloat)minHeight attributes:(NSDictionary*)attributes
{
    if (text) {
        CGSize size = CGSizeZero;
        CGSize rSize = CGSizeMake(width, NSUIntegerMax);
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0
        CGRect rect = [text boundingRectWithSize:rSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        size = rect.size;
#else
        UIFont *font = attributes[NSFontAttributeName];
        NSAssert(font, @"font不能为空");
        size = [text sizeWithFont:font constrainedToSize:rSize];
#endif
        if (size.height > minHeight) {
            return size.height;
        } else {
            return minHeight;
        }
    }
    
    return minHeight;
}

+ (CGFloat)widthWithText:(NSString *)text font:(UIFont *)font height:(CGFloat)height minWidth:(CGFloat)minWidth
{
    if (text) {
        CGSize size = CGSizeZero;
        CGSize rSize = CGSizeMake(NSUIntegerMax, height);
        
        size = [self sizeWithText:text boundingSize:rSize font:font lineBreakMode:NSLineBreakByCharWrapping];
        
        if (size.width > minWidth) {
            return size.width;
        } else {
            return minWidth;
        }
    }
    
    return minWidth;
}

+ (CGSize)sizeWithText:(NSString *)text boundingSize:(CGSize)boundingSize font:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode
{
    CGSize textSize;
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = lineBreakMode;
    NSDictionary *ats = @{
                          NSFontAttributeName : font,
                          NSParagraphStyleAttributeName : paragraphStyle
                          };
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0
    CGRect rect = [text boundingRectWithSize:boundingSize
                                     options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine
                                  attributes:ats
                                     context:nil];
    textSize        = rect.size;
    textSize.width  = ceil(textSize.width);
    textSize.height = ceil(textSize.height);
    
#else
    // -boundingRectWithSize:options:attributes:context: is available in iOS 7.0 and later
    if ( [text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)] ) {
        CGRect rect = [text boundingRectWithSize:boundingSize
                                         options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine
                                      attributes:ats
                                         context:nil];
        textSize        = rect.size;
        textSize.width  = ceil(textSize.width);
        textSize.height = ceil(textSize.height);
        
    }else{
        
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        textSize = [text sizeWithFont:font constrainedToSize:boundingSize lineBreakMode:lineBreakMode];
        textSize.width  = ceil(textSize.width);
        textSize.height = ceil(textSize.height);
#pragma clang diagnostic pop
        
    }
#endif
    return textSize;
}

+ (CGFloat)heightWithText:(NSString *)text boundingSize:(CGSize)boundingSize font:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode{
    CGSize size = [self sizeWithText:text boundingSize:boundingSize font:font lineBreakMode:lineBreakMode];
    return ceilf(size.height);
}

+ (CGFloat)heightForString:(NSString *)string font:(UIFont *)font lineSpacingPercent:(CGFloat)lineSpacingPercent width:(CGFloat)width{
    CGFloat lineSpacing = font.lineHeight * (lineSpacingPercent);
    return [self heightForString:string font:font lineSpacing:lineSpacing width:width];
}

+ (CGFloat)heightForString:(NSString *)string font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing width:(CGFloat)width{
    NSAttributedString *attributedStr = [self attributedStringFromText:string font:font color:[UIColor clearColor]  lineSpacing:lineSpacing lineBreakMode:NSLineBreakByCharWrapping];
    
    CGRect boundingRect = [attributedStr boundingRectWithSize:CGSizeMake(width, 999)
                                                      options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine
                                                      context:nil];
    return ceilf(CGRectGetHeight(boundingRect));
}

+ (NSAttributedString *)attributedStringFromText:(NSString *)text font:(UIFont *)font color:(UIColor *)textColor lineSpacing:(CGFloat)lineSpacing lineBreakMode:(NSLineBreakMode)lineBreakMode{
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 6 && text) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = lineSpacing;
        paragraphStyle.lineBreakMode = lineBreakMode;
        NSDictionary *ats = @{
                              NSFontAttributeName : font,
                              NSForegroundColorAttributeName : textColor,
                              NSParagraphStyleAttributeName : paragraphStyle
                              };
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString: text attributes: ats];
        return attributedText;
    }
    return nil;
}


+ (NSAttributedString *)attributedStringFromText:(NSString *)text font:(UIFont *)font color:(UIColor *)textColor lineSpacing:(CGFloat)lineSpacing lineBreakMode:(NSLineBreakMode)lineBreakMode textAlignment:(NSTextAlignment)textAlignment{
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 6 && text) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = lineSpacing;
        paragraphStyle.lineBreakMode = lineBreakMode;
        paragraphStyle.alignment = textAlignment;
        NSDictionary *ats = @{
                              NSFontAttributeName : font,
                              NSForegroundColorAttributeName : textColor,
                              NSParagraphStyleAttributeName : paragraphStyle
                              };
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString: text attributes: ats];
        return attributedText;
    }
    return nil;
 
}


+ (CGRect)getLabelSize:(UIFont*)font labelText:(NSString*)text andWidth:(CGFloat)width andLineSpace:(CGFloat)lineSpace andlimitedToNumberOfLines:(NSInteger)numberOfLines
{
    UILabel *label = [TKUtil createLabel:font color:[UIColor whiteColor]];
    label.text = text;
    NSAttributedString *attributedStr = [self attributedStringFromText:text font:font color:[UIColor whiteColor]  lineSpacing:lineSpace lineBreakMode:NSLineBreakByCharWrapping];
    label.attributedText = attributedStr;
    label.width = width;
    return [label textRectForBounds:CGRectMake(0, 0, label.width,FLT_MAX ) limitedToNumberOfLines:numberOfLines];
}

#pragma mark -

+ (NSString *)trimWhitespace:(NSString *)string
{
    return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
}

+ (UIViewAnimationOptions)animationOptionsForCurve:(UIViewAnimationCurve)curve
{
    switch (curve) {
        case UIViewAnimationCurveEaseInOut:
            return UIViewAnimationOptionCurveEaseInOut;
            break;
        case UIViewAnimationCurveEaseIn:
            return UIViewAnimationOptionCurveEaseIn;
            break;
        case UIViewAnimationCurveEaseOut:
            return UIViewAnimationOptionCurveEaseOut;
            break;
        case UIViewAnimationCurveLinear:
            return UIViewAnimationOptionCurveLinear;
            break;
    }
    
    return kNilOptions;
}

/**
 *    return the gray image of the raw image considering alpha
 *
 *    param image
 *
 *    @return gray image
 */
+ (UIImage*)convertImageToGreyScale:(UIImage*)image
{
    CGFloat w, h;
    switch (image.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            w = image.size.height;
            h = image.size.width;
            break;
        default:
            w = image.size.width;
            h = image.size.height;
    }
    CGRect imageRect = CGRectMake(0, 0, w, h);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

    //xcdoc://ios/documentation/GraphicsImaging/Reference/CGBitmapContext/Reference/reference.html
    //The constants for specifying the alpha channel information are declared with the CGImageAlphaInfo type but can be passed to this parameter safely.
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 0, colorSpace, (CGBitmapInfo)kCGImageAlphaNone);
    CGContextDrawImage(context, imageRect, image.CGImage);
    CGImageRef grayImage = CGBitmapContextCreateImage(context);

    CGContextRelease(context);
    context = CGBitmapContextCreate(NULL, w, h, 8, 0, NULL, (CGBitmapInfo)kCGImageAlphaOnly);
    CGContextDrawImage(context, imageRect, image.CGImage);
    CGImageRef mask = CGBitmapContextCreateImage(context);

    CGImageRef imageRef = CGImageCreateWithMask(grayImage, mask);
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation];

    CGImageRelease(mask);
    CGImageRelease(imageRef);
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CGImageRelease(grayImage);
    return result;
}

// UITextField Limit Max Lenght

+ (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string limitMaxLength:(NSUInteger)maxLength{
    
    NSString *shouldText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    //NSString *trimmedText = [shouldText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSInteger strLength = shouldText.length;
    if (strLength > maxLength) {
        // 允许删除
        if (strLength < textField.text.length) {
            return YES;
        }
        // 已经超长了，不允许输入更多
        return NO;
    }
    return YES;
}

+ (NSString *)truncateString:(NSString *)string maxLength:(NSInteger)maxLength{
    if (string.length <= maxLength) {
        return string;
    }
    NSString *truncStr = [string substringToIndex:maxLength];
    return truncStr;
}

#pragma mark -

+ (NSString *)appName
{
    NSString *name = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
    return name;
}

+ (NSString*)boundleIdentifier
{
    NSString *name = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
    return name;
}

+ (NSString *)appVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *version = infoDictionary[@"CFBundleShortVersionString"];
    
#if (defined(DEBUG) || defined(ADHOC))
    NSString *build = infoDictionary[@"CFBundleVersion"];
    version = [NSString stringWithFormat:@"v%@ build %@", version, build];
#else
    version = [@"v" stringByAppendingString:version];
#endif
    return version;
}

+ (NSString *)appMarketVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *version = infoDictionary[@"CFBundleShortVersionString"];
    return version;
}

+ (NSString *)appBuildVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *build = infoDictionary[@"CFBundleVersion"];
    return build;
}

+ (UIImage *)launchImage{
    UIImage *launchImage = nil;
    if (iPhone5) {
        launchImage = [UIImage imageNamed:@"LaunchImage-700-568h"];
    }else if (iPhone6) {
        launchImage = [UIImage imageNamed:@"LaunchImage-800-667h"];
    }else if (iPhone6P) {
        launchImage = [UIImage imageNamed:@"LaunchImage-800-Portrait-736h"];
    }else {
        launchImage = [UIImage imageNamed:@"LaunchImage-700"];
    }
    return launchImage;
}


#pragma mark -

+ (NSString *)md5:(NSString *)input {
    const char *cStr = [input UTF8String];
    unsigned char digest[16];
    CC_MD5( cStr, (unsigned int)strlen(cStr), digest );

    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];

    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];

    return  output;
}

+ (NSString *)formatTime:(NSDate *)formatDate with:(NSString *)format {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:format];
    return [dateFormat stringFromDate:formatDate];
}

@end
